package cn.ctyun.videoplayer.controller;

import android.content.Context;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import cn.ctyun.videoplayer.R;
import cn.ctyun.videoplayer.player.IjkVideoView;
import cn.ctyun.videoplayer.util.AnimHelper;
import cn.ctyun.videoplayer.util.NavUtils;
import cn.ctyun.videoplayer.util.SoftInputUtils;
import cn.ctyun.videoplayer.widget.DanmakuVideoView;

import master.flame.danmaku.danmaku.model.BaseDanmaku;

public class DanmakuController extends DefinitionController {

    private ImageView mOpenEditDanmaku;
    private ImageView mIvCancelSendDanmaku;
    private ImageView mIvDoSendDanmaku;

    // 无效变量
    private static final int INVALID_VALUE = -1;

    // 弹幕显示/隐藏按钮
    private ImageView mIvDanmakuControl;
//    // 弹幕编辑布局打开按钮
//    private TextView mTvOpenEditDanmaku;
//    // 使能弹幕才会显示的播放进度条
//    private SeekBar mDanmakuPlayerSeek;
//    // 使能弹幕才会显示时间分割线
//    private TextView mTvTimeSeparator;
    // 弹幕编辑布局
    private View mEditDanmakuLayout;
    // 弹幕内容编辑框
    private EditText mEtDanmakuContent;

    // 弹幕基础设置布局
    private View mDanmakuOptionsBasic;
    // 弹幕字体大小选项卡
    private RadioGroup mDanmakuTextSizeOptions;
    // 弹幕类型选项卡
    private RadioGroup mDanmakuTypeOptions;
    // 弹幕当前颜色
    private RadioButton mDanmakuCurColor;
    // 开关弹幕颜色选项卡
    private ImageView mDanmakuMoreColorIcon;
    // 弹幕更多颜色设置布局
    private View mDanmakuMoreOptions;
    // 弹幕颜色选项卡
    private RadioGroup mDanmakuColorOptions;

//    // 弹幕控制相关
//    private DanmakuContext mDanmakuContext;
//    // 弹幕解析器
//    private BaseDanmakuParser mDanmakuParser;
//    // 弹幕加载器
//    private ILoader mDanmakuLoader;
//    // 弹幕数据转换器
//    private BaseDanmakuConverter mDanmakuConverter;
//    // 弹幕监听器
//    private OnDanmakuListener mDanmakuListener;
    // 是否使能弹幕
    private boolean mIsEnableDanmaku = false;
    // 弹幕颜色
    private int mDanmakuTextColor = Color.WHITE;
    // 弹幕字体大小
    private float mDanmakuTextSize = INVALID_VALUE;
    // 弹幕类型
    private int mDanmakuType = BaseDanmaku.TYPE_SCROLL_RL;
    // 弹幕基础设置布局的宽度
    private int mBasicOptionsWidth = INVALID_VALUE;
    // 弹幕更多颜色设置布局宽度
    private int mMoreOptionsWidth = INVALID_VALUE;
    // 弹幕要跳转的目标位置，等视频播放再跳转，不然老出现只有弹幕在动的情况
    private long mDanmakuTargetPosition = INVALID_VALUE;



    public DanmakuController(@NonNull Context context) {
        super(context);
    }

    public DanmakuController(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public DanmakuController(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void initView() {
        super.initView();

        mIvDanmakuControl = findViewById(R.id.iv_danmaku_control); // 弹幕控制
        mIvDanmakuControl.setOnClickListener(this);
        mOpenEditDanmaku = mControllerView.findViewById(R.id.iv_open_edit_danmaku);
        mOpenEditDanmaku.setOnClickListener(this);
        mEditDanmakuLayout = findViewById(R.id.ll_edit_danmaku);
        mEtDanmakuContent = findViewById(R.id.et_danmaku_content);
        int navigationBarHeight = NavUtils.getNavigationBarHeight(getContext());
        if (navigationBarHeight > 0) {
            // 对于有虚拟键的设备需要将弹幕编辑布局右偏移防止被覆盖
            mEditDanmakuLayout.setPadding(0, 0, navigationBarHeight, 0);
        }
        mIvCancelSendDanmaku = mControllerView.findViewById(R.id.iv_cancel_send);
        mIvCancelSendDanmaku.setOnClickListener(this);
        mIvDoSendDanmaku = mControllerView.findViewById(R.id.iv_do_send);
        mIvDoSendDanmaku.setOnClickListener(this);

        mIvDanmakuControl.setSelected(false);

//        if (mIvDanmakuControl.isSelected()) {
//            mOpenEditDanmaku.setVisibility(GONE);
//        } else {
//            mOpenEditDanmaku.setVisibility(VISIBLE);
//        }


        // 这些为弹幕配置处理
        int oneBtnWidth = getResources().getDimensionPixelOffset(R.dimen.danmaku_input_options_color_radio_btn_size);
        // 布局宽度为每个选项卡宽度 * 12 个，有12种可选颜色
        mMoreOptionsWidth = oneBtnWidth * 12;
        mDanmakuOptionsBasic = findViewById(R.id.input_options_basic);
        mDanmakuMoreOptions = findViewById(R.id.input_options_more);
        mDanmakuMoreOptions.setOnClickListener(this);
        mDanmakuCurColor = (RadioButton) findViewById(R.id.input_options_color_current);
        mDanmakuMoreColorIcon = (ImageView) findViewById(R.id.input_options_color_more_icon);
        mDanmakuTextSizeOptions = (RadioGroup) findViewById(R.id.input_options_group_textsize);
        mDanmakuTypeOptions = (RadioGroup) findViewById(R.id.input_options_group_type);
        mDanmakuColorOptions = (RadioGroup) findViewById(R.id.input_options_color_group);
        mDanmakuTextSizeOptions.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.input_options_small_textsize) {
                    mDanmakuTextSize = 25f * (((DanmakuVideoView)mMediaPlayer).getDanmakuParser().getDisplayer().getDensity() - 0.6f) * 0.7f;
                } else if (checkedId == R.id.input_options_medium_textsize) {
                    mDanmakuTextSize = 25f * (((DanmakuVideoView)mMediaPlayer).getDanmakuParser().getDisplayer().getDensity() - 0.6f);
                }
            }
        });
        mDanmakuTypeOptions.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.input_options_rl_type) {
                    mDanmakuType = BaseDanmaku.TYPE_SCROLL_RL;
                } else if (checkedId == R.id.input_options_top_type) {
                    mDanmakuType = BaseDanmaku.TYPE_FIX_TOP;
                } else if (checkedId == R.id.input_options_bottom_type) {
                    mDanmakuType = BaseDanmaku.TYPE_FIX_BOTTOM;
                }
            }
        });
        mDanmakuColorOptions.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // 取的是 tag 字符串值，需转换为颜色
                String color = (String) findViewById(checkedId).getTag();
                mDanmakuTextColor = Color.parseColor(color);
                mDanmakuCurColor.setBackgroundColor(mDanmakuTextColor);
            }
        });
    }

    @Override
    public void setMediaPlayer(BaseMediaPlayerControlInterface mediaPlayer) {
        super.setMediaPlayer(mediaPlayer);
        if (mediaPlayer != null) {
            if (!((DanmakuControllerInterfaceBase) mMediaPlayer).isDanmakuEnable()) {
                mIvDanmakuControl.setVisibility(GONE);
                mOpenEditDanmaku.setVisibility(GONE);
            }
            if (!((DanmakuControllerInterfaceBase) mMediaPlayer).isDanmakuEnable()) {
                mDLNAButton.setVisibility(GONE);
            }
        }
    }

    public void enableDanmaku() {
        mIvDanmakuControl.setVisibility(VISIBLE);
    }

    public void showDanmakuInit() {
        mIvDanmakuControl.setSelected(true);
    }

    @Override
    public void setPlayerState(int playerState) {
        super.setPlayerState(playerState);
        switch (playerState) {
            case IjkVideoView.PLAYER_NORMAL:
                mOpenEditDanmaku.setVisibility(GONE); // 竖屏不可发送弹幕
                break;
            case IjkVideoView.PLAYER_FULL_SCREEN:
                if (mShowing) {
                    if (mIvDanmakuControl.isSelected()) {
                        mOpenEditDanmaku.setVisibility(VISIBLE);
                    } else {
                        mOpenEditDanmaku.setVisibility(GONE);
                    }
                }
                break;
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        int i = v.getId();
        if (i == R.id.iv_danmaku_control) {
            _toggleDanmakuShow();
        } else if (i == R.id.iv_open_edit_danmaku) {
//            if (mDanmakuListener == null || mDanmakuListener.isValid()) {
            editVideo();
            mEditDanmakuLayout.setVisibility(VISIBLE);
            SoftInputUtils.setEditFocusable(mAttachActivity, mEtDanmakuContent);
//            }
        }
        else if (i == R.id.iv_cancel_send) {
            recoverFromEditVideo();
        } else if (i == R.id.iv_do_send) {
            recoverFromEditVideo();
            if (mMediaPlayer instanceof DanmakuControllerInterfaceBase) {
                if (mDanmakuTextSize == INVALID_VALUE) {
                    mDanmakuTextSize = 25f * (((DanmakuVideoView)mMediaPlayer).getDanmakuParser().getDisplayer().getDensity() - 0.6f);
                }
                ((DanmakuControllerInterfaceBase) mMediaPlayer).sendDanmu(mDanmakuType,
                        mEtDanmakuContent.getText().toString(), mDanmakuTextSize, mDanmakuTextColor, false);
                mEtDanmakuContent.setText("");
            }
        } else if (i == R.id.input_options_more) {
            _toggleMoreColorOptions();
        }
    }

    public void selectDanmakuControl(boolean isSelected) {
        mIvDanmakuControl.setSelected(isSelected);
    }

    /**
     * 切换弹幕的显示/隐藏
     */
    private void _toggleDanmakuShow() {
        if (mIvDanmakuControl.isSelected()) {
            mOpenEditDanmaku.setVisibility(GONE);
            showOrHideDanmaku(false);
        } else {
            // 横屏才显示此按钮
            if (IjkVideoView.PLAYER_FULL_SCREEN == mCurrentPlayerState) {
                mOpenEditDanmaku.setVisibility(VISIBLE);
            }

            showOrHideDanmaku(true);
        }
    }

    /**
     * 显示/隐藏弹幕
     *
     * @param isShow 是否显示
     * @return
     */
    public void showOrHideDanmaku(boolean isShow) {
        if (isShow) {
            mIvDanmakuControl.setSelected(true);
        } else {
            mIvDanmakuControl.setSelected(false);
        }
        if (mMediaPlayer instanceof DanmakuControllerInterfaceBase) {
            ((DanmakuControllerInterfaceBase) mMediaPlayer).showOrHideDanmaku(isShow);
        }
    }

    /**
     * 编辑操作前调用，会控制视频的播放状态，如在编辑弹幕前调用，配合{@link #recoverFromEditVideo()}使用
     */
    public void editVideo() {
        if (mMediaPlayer.isPlaying()) {
            mMediaPlayer.pause();
        }
        hideAllViews();
//        if (mVideoView.isPlaying()) {
//            pause();
//            mVideoStatus = INTERRUPT_WHEN_PLAY;
//        } else {
//            mVideoStatus = INTERRUPT_WHEN_PAUSE;
//        }
//        _hideAllView(false);
    }

    /**
     * 从编辑状态返回，如取消编辑或发射弹幕后配合{@link #editVideo()}调用
     *
     * @return 是否从编辑状态回退
     */
    public boolean recoverFromEditVideo() {
//        if (mVideoStatus == NORMAL_STATUS) {
//            return false;
//        }
        if (mMediaPlayer.isFullScreen()) {
            _recoverScreen();
        }
//        if (mVideoStatus == INTERRUPT_WHEN_PLAY) {
//            start();
//        }
//        mVideoStatus = NORMAL_STATUS;
        if (!mMediaPlayer.isPlaying()) {
            mMediaPlayer.start();
        }
        return true;
    }

    /**
     * 从弹幕编辑状态复原界面
     */
    private void _recoverScreen() {
        // 清除焦点
//        mEditDanmakuLayout.clearFocus();
        mEditDanmakuLayout.setVisibility(GONE);
//        mEtDanmakuContent.setFocusable(false);
//        mEtDanmakuContent.setFocusableInTouchMode(true);
        // 关闭软键盘
        SoftInputUtils.closeSoftInput(mEtDanmakuContent, mAttachActivity);
        // 重新设置全屏界面UI标志位
//        _setUiLayoutFullscreen();
//        if (mDanmakuColorOptions.getWidth() != 0) {
//            _toggleMoreColorOptions();
//        }
//        showAllViews();
    }


    /**
     * 动画切换弹幕颜色选项卡显示
     */
    private void _toggleMoreColorOptions() {
        if (mBasicOptionsWidth == INVALID_VALUE) {
            mBasicOptionsWidth = mDanmakuOptionsBasic.getWidth();
        }
        if (mDanmakuColorOptions.getWidth() == 0) {
            AnimHelper.doClipViewWidth(mDanmakuOptionsBasic, mBasicOptionsWidth, 0, 300);
            AnimHelper.doClipViewWidth(mDanmakuColorOptions, 0, mMoreOptionsWidth, 300);
            ViewCompat.animate(mDanmakuMoreColorIcon).rotation(180).setDuration(150).setStartDelay(250).start();
        } else {
            AnimHelper.doClipViewWidth(mDanmakuOptionsBasic, 0, mBasicOptionsWidth, 300);
            AnimHelper.doClipViewWidth(mDanmakuColorOptions, mMoreOptionsWidth, 0, 300);
            ViewCompat.animate(mDanmakuMoreColorIcon).rotation(0).setDuration(150).setStartDelay(250).start();
        }
    }


    @Override
    public void setPlayState(int playState) {
        super.setPlayState(playState);
        switch (playState) {
            case IjkVideoView.STATE_PLAYBACK_COMPLETED:
//                Toast.makeText(mAttachActivity, "dasdasd", Toast.LENGTH_SHORT).show();
                ((DanmakuControllerInterfaceBase) mMediaPlayer).releaseDanmaku();
//                showOrHideDanmaku(false);
                break;
        }
    }
}
